package com.itheima.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
//开启注解控制权限, prePostEnabled = true 允许使用@PreAuthorize (前置,(常用)), @PostAuthorize（后置）
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder;

    }


    //配置UserDetailsService, 指定那些用户可以访问该系统
//    @Bean
//    @Override
//    public UserDetailsService userDetailsServiceBean(){
        //在内存中构建用户
//        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
//        //构建的用户密码不加密（noop）
//        inMemoryUserDetailsManager.createUser(User.withUsername("itcast")
//                                    .password(passwordEncoder().encode("123456"))
//                                    .authorities("P1","ROLE_ADMIN").build());
//        inMemoryUserDetailsManager.createUser( User.withUsername("itheima")
//                .password(passwordEncoder().encode("123456"))
//                .authorities("O1","ROLE_USER").build());
//
//        return inMemoryUserDetailsManager;
//    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()////表单登录   只要表单是 /login 就认为你在登录
                .and()
                .logout().and()  //退出功能  只要请求/logout就会清除session，跳转到登录页面
                .csrf().disable()  //关闭跨站请求伪造
                .authorizeRequests()  //认证请求配置
            .antMatchers("/register").permitAll() //不登录即可访问
//            .antMatchers("/hello").hasAuthority("P1") //具有P1权限才可以访问
//            .antMatchers("/say").hasRole("USER") //具有SELLER 角色才可以访问
            .anyRequest().authenticated(); //其他的登录之后就可以访问
    }
}
